package com.yupi.yupicturebackend.manager;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 废弃的类
 */

@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片到COS
     *
     * @param multipartFile
     * @param uploadPathPrefix
     * @return
     */
    public  UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        //校验图片参数
        validPicture(multipartFile);
        //组合上传路径信息 请求头+操作时间+uuid+文件名后缀
        String uuid = RandomUtil.randomString(16);
        String fileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(multipartFile.getOriginalFilename()));
        String filePath = String.format("%s/%s", uploadPathPrefix, fileName);
        //上传信息到COS
        File file = null;
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        try {
           file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(filePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
//          封装图片返回信息
            double round = NumberUtil.round(imageInfo.getWidth() * 1.0 / imageInfo.getHeight(), 2).doubleValue();
            uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+filePath);
            uploadPictureResult.setPicName(fileName);
            uploadPictureResult.setPicSize(multipartFile.getSize());
            uploadPictureResult.setPicWidth(imageInfo.getWidth());
            uploadPictureResult.setPicHeight(imageInfo.getHeight());
            uploadPictureResult.setPicScale(round);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
        } catch (IOException e) {
            log.info("图片存储上传失败", e);
            e.printStackTrace();
        } finally {
            if (file!=null){
                file.delete();
            }if (file==null){
                log.error("临时文件不纯在, filePath = {}" ,filePath);
            }
        }
        //返回上传结果
        return uploadPictureResult;
    }
    /**
     * 通过url上传图片
     *
     * @param fileUrl
     * @param uploadPathPrefix
     * @return
     */
    public  UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        //校验图片参数

        validPicture(fileUrl);
        //组合上传路径信息 请求头+操作时间+uuid+文件名后缀
        String uuid = RandomUtil.randomString(16);
        String originalFileName = FileUtil.mainName(fileUrl);
        String fileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFileName));
        String filePath = String.format("%s/%s", uploadPathPrefix, fileName);
        //上传信息到COS
        File file = null;
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        try {
            file = File.createTempFile(filePath, null);
//            multipartFile.transferTo(file);

//            下载文件
             HttpUtil.downloadFile(fileUrl, file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(filePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
//          封装图片返回信息
            double round = NumberUtil.round(imageInfo.getWidth() * 1.0 / imageInfo.getHeight(), 2).doubleValue();
            uploadPictureResult.setUrl(cosClientConfig.getHost()+"/"+filePath);
            uploadPictureResult.setPicName(FileUtil.getName(file));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(imageInfo.getWidth());
            uploadPictureResult.setPicHeight(imageInfo.getHeight());
            uploadPictureResult.setPicScale(round);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
        } catch (IOException e) {
            log.info("图片存储上传失败", e);
            e.printStackTrace();
        } finally {
            if (file!=null){
                file.delete();
            }if (file==null){
                log.error("临时文件不纯在, filePath = {}" ,filePath);
            }
        }
        //返回上传结果
        return uploadPictureResult;
    }
    /**
     * URL 图片上传
     */
        protected void validPicture(Object inputSource) {
            String fileUrl = (String) inputSource;
            // 1. 校验非空
            ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址为空");

            // 2. 校验 URL 格式
            try {
                new URL(fileUrl);
            } catch (MalformedURLException e) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
            }
            // 3. 校验 URL 的协议
            ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),
                    ErrorCode.PARAMS_ERROR, "仅支持 HTTP 或 HTTPS 协议的文件地址"
            );
            // 4. 发送 HEAD 请求验证文件是否存在
            HttpResponse httpResponse = null;
            try {
                httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl)
                        .execute();
                // 未正常返回，无需执行其他判断
                if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                    return;
                }
                // 5. 文件存在，文件类型校验
                String contentType = httpResponse.header("Content-Type");
                // 不为空，才校验是否合法，这样校验规则相对宽松
                if (StrUtil.isNotBlank(contentType)) {
                    // 允许的图片类型
                    final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                    ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                            ErrorCode.PARAMS_ERROR, "文件类型错误");
                }
                // 6. 文件存在，文件大小校验
                String contentLengthStr = httpResponse.header("Content-Length");
                if (StrUtil.isNotBlank(contentLengthStr)) {
                    try {
                        long contentLength = Long.parseLong(contentLengthStr);
                        final long ONE_M = 1024 * 1024;
                        ThrowUtils.throwIf(contentLength > 2 * ONE_M, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2MB");
                    } catch (NumberFormatException e) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式异常");
                    }
                }
            } finally {
                // 记得释放资源
                if (httpResponse != null) {
                    httpResponse.close();
                }
            }
        }


        protected String getOriginFilename(Object inputSource) {
            String fileUrl = (String) inputSource;
            return FileUtil.mainName(fileUrl);
        }


        protected void processFile(Object inputSource, File file) throws Exception {
            String fileUrl = (String) inputSource;
            // 下载文件到临时目录
            HttpUtil.downloadFile(fileUrl, file);
        }





    /**
     * 校验图片参数
     *
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        //校验文件是否为空或是否大于2M
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);
        long size = multipartFile.getSize();
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_M * 2, ErrorCode.PARAMS_ERROR, "文件大小超过2M");
        //校验文件格式
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> SUFFIX_ARRAY = Arrays.asList("png", "jpg", "jpeg", "webp", "svg");
        ThrowUtils.throwIf(!SUFFIX_ARRAY.contains(suffix), ErrorCode.PARAMS_ERROR, "不支持的文件类型");
    }
}
